<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="试卷名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入试卷名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索
        </el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置
        </el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['exam:add']"
        >新增
        </el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>


    <el-table
      ref="tables"
      v-loading="loading"
      :data="paperList"
    >
      <el-table-column label="ID" align="center" prop="id"/>
      <el-table-column label="考试名称" align="center" prop="name"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="试题ID" align="center" prop="questionIds">
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="startTime" >
        <template slot-scope="scope">
              <span>{{
                  parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
                }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="endTime" >
        <template slot-scope="scope">
              <span>{{
                  parseTime(scope.row.updateTime, "{y}-{m}-{d} {h}:{i}:{s}")
                }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-row>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['exam:paper:update']"
            >编辑
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDel(scope.row)"
              v-hasPermi="['exam:paper:del']"
            >删除
            </el-button>
            <router-link :to="'/paperView/index/' + scope.row.id" class="link-type">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                style="padding:5px"
                v-hasPermi="['exam:paper:list']"
              >预览</el-button>
            </router-link>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-minus"
              @click="handleRemoveQuestion(scope.row)"
              v-hasPermi="['exam:paper:update']"
            >删减试题
            </el-button>
            <router-link :to=" '/questionBank/list'" class="link-type">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-plus"
                style="padding:5px"
                v-hasPermi="['questionBank:query']"
              >添加试题</el-button>
            </router-link>
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增试卷 -->
    <el-dialog title="新增试卷" :visible.sync="addData.open" width="400px" append-to-body>
      <el-form ref="form" :model="addData.data"  label-width="140px">
        <el-form-item label="试卷名称" prop="name">
          <el-input v-model="addData.data.name" placeholder="请输入试卷名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="addData.data.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <router-link :to=" '/questionBank/list'" class="link-type">
        <el-button
          size="mini"
          type="text"
          icon="el-icon-view"
          style="padding:5px"
          v-hasPermi="['questionBank:query']"
        >前往题库</el-button>
      </router-link>
      <div slot="footer" class="dialog-footer">

        <el-button type="primary" @click="submitAddForm">确 定</el-button>
        <el-button @click="addData.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 编辑试卷 -->
    <el-dialog title="编辑试卷" :visible.sync="updateData.open" width="400px" append-to-body>
      <el-form ref="form" :model="updateData.data"  label-width="140px">
        <el-form-item label="试卷名称" prop="name">
          <el-input v-model="updateData.data.name" placeholder="请输入试卷名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="updateData.data.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpdateForm">确 定</el-button>
        <el-button @click="updateData.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="删减试题" :visible.sync="removeData.open" width="900px" append-to-body>
      <el-table
        ref="tables"
        :data="removeData.data.questionDataList"
        @selection-change="handleRemoveSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="编号" align="center" prop="id"/>
        <el-table-column label="题干" align="center" prop="content"/>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmitRemoveQuestion">确 定</el-button>
        <el-button @click="updateData.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listTextbook, addTextBook, updateTextBook, read, delTextBook, info } from '@/api/exam/textbook'
import { isArray } from 'util'
import { getToken } from '@/utils/auth'
import { delQuestion } from '@/api/questionBank/question'
import { addPaper, del, listPaper, removeQuestion, updatePaper } from '@/api/exam/paper'

export default {
  name: 'ExamPaper',
  data() {
    return {
      queryParams: {
        name: null,

        pageNo: 1,
        pageSize: 10,
      },
      showSearch: true,

      paperList: [],
      loading: false,
      total: 0,

      addData:{
        open: false,
        data: {

        },
        formRule: {
          name: [{ required: true, message: "试卷名称不能为空", trigger: "blur" }],
          remark: [{ required: true, message: "备注不能为空", trigger: "blur" }],
        }
      },

      updateData:{
        open: false,
        data: {

        },
        formRule: {
          name: [{ required: true, message: "试卷名称不能为空", trigger: "blur" }],
          remark: [{ required: true, message: "备注不能为空", trigger: "blur" }],
        }
      },
      removeData: {
        open: false,
        data: {},
      },
      reader: {
        open: false,
        data: null,
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询任务列表 */
    getList() {
      this.loading = true
      let param = {...this.queryParams};
      param.pageNo --;
      listPaper(param).then(
        (response) => {
          this.paperList = response.rows
          this.total = parseInt(response.total)
          this.loading = false
        }
      )
    },

    statusVal(status) {
      for (let s of this.examStatus) {
        if (s.status == status) {
          return s.label
        }
      }
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.startDateRange = []
      this.endDateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },

    /** 详细按钮操作 */
    handleView(row) {
      this.taskNo = row.taskNo
      this.taskView = true
      const taskId = row.taskId
      getTask(taskId).then((response) => {
        this.evaluate = response.data
        this.title = '考核详情'
      })

      //人员信息
      this.getPersonlTaskList()
    },

    handleAdd() {
      this.addData.open = true
    },

    handleImport() {
      this.upload.title = '题目导入'
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('questionBank/question/importTemplate', {}, `题目导入模板.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.upload.data.id = response.data.id
      updateTextBook(this.upload.data).then(resp => {
        this.$alert('<div style=\'overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;\'>' + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
        this.getList()
      })
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },

    handleRead(row) {
      this.reader.open = true
      this.reader.loading = true
      info(row['id']).then(response => {
        let info = response.data;
        this.reader.type = info.type;
        if(this.reader.type == 0){
          read(row['id']).then(resp => {
            let binaryData = []
            binaryData.push(resp)// res 后台返回的流数据
            let pdfUrl = ''
            pdfUrl = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }))
            this.reader.src = pdfUrl
            this.reader.loading = false
          })
        }else {
          this.reader.src = process.env.VUE_APP_BASE_API + '/textbook/read?id='+ row['id'] +'&Authorization=' + getToken();
        }
      })

      // this.reader.src = process.env.VUE_APP_BASE_API + '/textbook/read?id=' + row['id'];
    },
    handleDel(row) {
      this.$confirm('是否确认删除试卷【'+ row.name +'】?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(row.id).then(resp => {
          this.getList();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
      });
    },
    handleUpdate(row) {
      this.updateData.data = row;
      this.updateData.open = true;
    },

    handleRemoveQuestion(row){
      this.removeData.open = true;
      this.removeData.data = {...row};
    },
    handleRemoveSelectionChange(selection){
      this.removeData.data.questionIds = selection.map(item => item.id);
    },
    onSubmitRemoveQuestion(){
      if(!this.removeData.data.questionIds){
        return;
      }
      removeQuestion({'id': this.removeData.data.id ,'questionIds': this.removeData.data.questionIds }).then(resp => {
        this.getList();
        this.removeData.open = false;
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      });
    },

    onAddExamFormTimeChange(val) {
      console.log(val)
      this.addExamForm.startTime = Date.parse(new Date(val[0])) / 1000
      this.addExamForm.endTime = Date.parse(new Date(val[1])) / 1000
    },
    onUpdateExamFormTimeChange(val) {
      this.updateExamForm.startTime = Date.parse(new Date(val[0])) / 1000
      this.updateExamForm.endTime = Date.parse(new Date(val[1])) / 1000
    },
    /** 提交新增*/
    submitAddForm() {
      if (!this.checkSubmitData(this.addData.data, this.addData.formRule)) {
        return
      }
      addPaper(this.addData.data).then(resp => {
        this.getList()
        this.addData.open = false
      })
    },
    submitUpdateForm() {
      if (!this.checkSubmitData(this.updateData.data, this.updateData.formRule)) {
        return
      }
      updatePaper(this.updateData.data).then(resp => {
        this.updateData.open = false
        this.getList()
      })
    },
    checkSubmitData(data, rules) {
      for (let key in rules) {
        if (rules[key][0] && rules[key][0].required) {
          if (!data[key] || (isArray(data[key]) && data[key].length == 0)) {
            this.$modal.msgError(rules[key][0].message)
            return false
          }
        }
      }
      return true
    }
  }
}
</script>
